package com.itboye.ihomebank;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import org.greenrobot.greendao.database.Database;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application.ActivityLifecycleCallbacks;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.ihomebank.adapter.KeyAdapter;
import com.itboye.ihomebank.base.BaseFragment;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.BangDingBean;
import com.itboye.ihomebank.bean.KeyBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.controller.LoginController;
import com.itboye.ihomebank.db.MyKeyService;
import com.itboye.ihomebank.key.ActivityGuanLiKey;
import com.itboye.ihomebank.key.ActivityGuanLiKeyTwo;
import com.itboye.ihomebank.key.ActivityKeyYuYue;
import com.itboye.ihomebank.key.ActivityMyKeySouSuo;
import com.itboye.ihomebank.key.ActivityPuTongKey;
import com.itboye.ihomebank.key.ActivitySheBei;
import com.itboye.ihomebank.login.LoginActivity;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.sliblistview.SwipeMenu;
import com.itboye.ihomebank.sliblistview.SwipeMenuCreator;
import com.itboye.ihomebank.sliblistview.SwipeMenuItem;
import com.itboye.ihomebank.sliblistview.SwipeMenuListView;
import com.itboye.ihomebank.sliblistview.SwipeMenuListView.OnMenuItemClickListener;
import com.itboye.ihomebank.ttKey.BleConstant;
import com.itboye.ihomebank.ttKey.BleSession;
import com.itboye.ihomebank.ttKey.DaoMaster;
import com.itboye.ihomebank.ttKey.DaoSession;
import com.itboye.ihomebank.ttKey.DbService;
import com.itboye.ihomebank.ttKey.Key;
import com.itboye.ihomebank.ttKey.KeyDao;
import com.itboye.ihomebank.ttKey.MyPreference;
import com.itboye.ihomebank.ttKey.Operation;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.ttlock.bl.sdk.api.TTLockAPI;
import com.ttlock.bl.sdk.callback.TTLockCallback;
import com.ttlock.bl.sdk.scanner.ExtendedBluetoothDevice;

/**
 * 钥匙
 * 
 */
public class KeyFragment extends BaseFragment implements OnClickListener,
		Observer {
	ImageView close_icon;
	TextView save;
	TextView img_nodata;
	TextView add_shap_title_tv;
	SwipeMenuListView xlistview;
	TextView mykey_sousuo;// 搜索
	UserPresenter userPresenter;
	KeyPresenter keyPresenter;

	// 保存绑定管理员后的一些密码，用来备份用
	String adminPs01;
	String adminKeyboardPwd01;
	String deletePwd01;

	String pwdInfo01;
	long timestamp01;

	String uid;
	private List<KeyBean> keyBean;
	private String type;
	private String lockid;
	public static String REDIRECT_URI = "http://api.ihomebank.com/public/index.php/sciener";

	static String access_token;

	public ProgressDialog progressDialog;
	Map<String, String> map = new HashMap<String, String>();
	public static KeyFragment context;

	public static String TAG = "keyfragment";

	private String deKeyId;// 删除的是哪一个钥匙

	/**
	 * 访问令牌
	 */
	private String accessToken;

	private KeyAdapter adapter;// 钥匙适配器

	/**
	 * 记录当前点击的key
	 */
	public static KeyBean curKey;
	private static boolean DBG = true;

	public static final boolean ENCRYPTED = true;

	public static Context mContext;

	private static DaoSession daoSession;

	public static KeyDao keyDao;

	private Activity curActivity;

	/**
	 * 默认备份密码
	 */
	public static final String defaultBackupPwd = "123456";

	/**
	 * 蓝牙操作
	 */
	public static BleSession bleSession = BleSession.getInstance(
			Operation.UNLOCK, null);

	/**
	 * 通通锁
	 */
	public static TTLockAPI mTTLockAPI;

	private Handler handler = new Handler();

	MyKeyService myKeyService;
	
	LinearLayout liner_nokey;//没有钥匙的时候
	TextView mykey_add,mykey_yuyue;

	@Override
	public int initView() {
		return R.layout.activity_my_key;
	}

	public static KeyFragment getInstance() {
		return context;
	}

	/**
	 * 通通锁回调
	 */
	private TTLockCallback mTTLockCallback = new TTLockCallback() {
		/**
		 * 发现设备
		 */
		@Override
		public void onFoundDevice(
				ExtendedBluetoothDevice extendedBluetoothDevice) {
			System.out.println(TAG + "发现设备"
					+ extendedBluetoothDevice.getAddress());
			// 发现设备并广播
			// broadcastUpdate(BleConstant.ACTION_BLE_DEVICE,
			// BleConstant.DEVICE, extendedBluetoothDevice);
			broadcastUpdate(BleConstant.ACTION_BLE_DEVICE, BleConstant.DEVICE,
					extendedBluetoothDevice);
			String accessToken = MyPreference.getStr(mContext,
					MyPreference.ACCESS_TOKEN);
			Key localKey = DbService.getKeyByAccessTokenAndLockmac(accessToken,
					extendedBluetoothDevice.getAddress());
			// Key localKey =
			// DbService.getKeyByAccessTokenAndLockmac(accessToken,
			// bleSession.getLockmac());
			if (localKey != null) {
				switch (bleSession.getOperation()) {
				case UNLOCK:

					if (ActivityGuanLiKey.addLock) {
						ActivityGuanLiKey.addLock = false;
						mTTLockAPI.connect(extendedBluetoothDevice);

						System.out.println(TAG + "当点击开锁"
								+ extendedBluetoothDevice.getAddress());
					}
					if (ActivityGuanLiKeyTwo.addLock) {
						ActivityGuanLiKeyTwo.addLock = false;
						mTTLockAPI.connect(extendedBluetoothDevice);

						System.out.println(TAG + "备份钥匙的点击");
					}
					if (ActivityPuTongKey.addLock) {
						ActivityPuTongKey.addLock = false;
						mTTLockAPI.connect(extendedBluetoothDevice);

						System.out.println(TAG + "普通钥匙的点击");
					}

					break;
				case SET_ADMIN_KEYBOARD_PASSWORD:
				case SET_DELETE_PASSWORD:
				case SET_LOCK_TIME:
				case RESET_KEYBOARD_PASSWORD:
				case RESET_EKEY:
				case RESET_LOCK:
				case GET_LOCK_TIME:
				case GET_OPERATE_LOG:
					if (extendedBluetoothDevice.getAddress().equals(
							bleSession.getLockmac()))
						mTTLockAPI.connect(extendedBluetoothDevice);
					break;
				default:
					break;

				}
			}
		}

		@Override
		public void onDeviceConnected(
				ExtendedBluetoothDevice extendedBluetoothDevice) {

			System.out.println(TAG + "连接成功的回调"
					+ extendedBluetoothDevice.getAddress());

			String accessToken = MyPreference.getStr(mContext,
					MyPreference.ACCESS_TOKEN);
			Key localKey = DbService.getKeyByAccessTokenAndLockmac(accessToken,
					extendedBluetoothDevice.getAddress());
			// Key localKey =
			// DbService.getKeyByAccessTokenAndLockmac(accessToken,
			// bleSession.getLockmac());

			// TODO:目前uid传0即可
			int uid = 0;

			switch (bleSession.getOperation()) {
			case ADD_ADMIN:
				// TODO:判断本地是否存在
				mTTLockAPI.addAdministrator(extendedBluetoothDevice);
				break;
			case UNLOCK:
				if (localKey != null) {// 本地存在锁
					if (!localKey.isAdmin()) {
						System.out.println(TAG + "普通开锁");
						mTTLockAPI.unlockByUser(extendedBluetoothDevice, 0,
								localKey.getLockVersion(),
								localKey.getStartDate(), localKey.getEndDate(),
								localKey.getUnlockKey(),
								localKey.getLockFlagPos(),
								localKey.getAesKeystr());
					} else {
						System.out.println(TAG + "管理员开锁"
								+ localKey.getLockMac());
						mTTLockAPI.unlockByAdministrator(
								extendedBluetoothDevice, 0,
								localKey.getLockVersion(),
								localKey.getAdminPs(), localKey.getUnlockKey(),
								localKey.getLockFlagPos(),
								System.currentTimeMillis(),
								localKey.getAesKeystr());
					}
				}
				break;

			default:
				break;
			}

		}

		@Override
		public void onDeviceDisconnected(
				ExtendedBluetoothDevice extendedBluetoothDevice) {
			// 默认是开门标志
			// bleSession.setOperation(Operation.UNLOCK);
			// 断开连接
			broadcastUpdate(BleConstant.ACTION_BLE_DISCONNECTED,
					BleConstant.DEVICE, extendedBluetoothDevice);
		}

		/**
		 * 添加管理员
		 */
		@Override
		public void onAddAdministrator(
				ExtendedBluetoothDevice extendedBluetoothDevice,
				String lockVersionString, String adminPs, String unlockKey,
				String adminKeyboardPwd, String deletePwd, String pwdInfo,
				long timestamp, String aesKeystr, int arg9,
				com.ttlock.bl.sdk.entity.Error error) {
			System.out.println("添加管理员" + error.getErrorMsg() + "");
			// ByAlert.alert("添加管理员"+error+"");
			if (error == error.SUCCESS) {// 成功

				// TODO:save数据
				final Key key = new Key();
				key.setAccessToken(MyPreference.getStr(mContext,
						MyPreference.ACCESS_TOKEN));
				key.setAdmin(true);
				key.setLockVersion(lockVersionString);
				key.setLockName(extendedBluetoothDevice.getName());
				key.setLockMac(extendedBluetoothDevice.getAddress());
				key.setAdminPs(adminPs);
				key.setUnlockKey(unlockKey);
				key.setAdminKeyboardPwd(adminKeyboardPwd);
				key.setDeletePwd(deletePwd);
				key.setPwdInfo(pwdInfo);
				key.setTimestamp(timestamp);
				key.setAesKeystr(aesKeystr);
				key.setId(keyDao.insert(key));
				curActivity.finish();

				adminPs01 = adminPs;
				adminKeyboardPwd01 = adminKeyboardPwd;
				deletePwd01 = deletePwd;
				pwdInfo01 = pwdInfo;
				timestamp01 = timestamp;

				keyPresenter.getAddMain(uid, "6323", key.getLockName(),
						key.getLockName(), key.getLockMac(), unlockKey, "0",
						aesKeystr.toString(), lockVersionString.toString());
			}
		}

		@Override
		public void onAddICCard(ExtendedBluetoothDevice arg0, int arg1,
				long arg2, com.ttlock.bl.sdk.entity.Error arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAddKeyboardPassword(ExtendedBluetoothDevice arg0,
				int arg1, String arg2, long arg3, long arg4,
				com.ttlock.bl.sdk.entity.Error arg5) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onClearICCard(ExtendedBluetoothDevice arg0, int arg1,
				com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onDeleteAllKeyboardPassword(ExtendedBluetoothDevice arg0,
				com.ttlock.bl.sdk.entity.Error arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onDeleteICCard(ExtendedBluetoothDevice arg0, int arg1,
				long arg2, com.ttlock.bl.sdk.entity.Error arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onDeleteOneKeyboardPassword(ExtendedBluetoothDevice arg0,
				int arg1, String arg2, com.ttlock.bl.sdk.entity.Error arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onGetLockTime(ExtendedBluetoothDevice arg0, long arg1,
				com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onGetOperateLog(ExtendedBluetoothDevice arg0, String arg1,
				com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onModifyICCardPeriod(ExtendedBluetoothDevice arg0,
				int arg1, long arg2, long arg3, long arg4,
				com.ttlock.bl.sdk.entity.Error arg5) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onResetEKey(ExtendedBluetoothDevice arg0, int arg1,
				com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onResetKeyboardPassword(ExtendedBluetoothDevice arg0,
				String arg1, long arg2, com.ttlock.bl.sdk.entity.Error arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onResetKeyboardPasswordProgress(
				ExtendedBluetoothDevice arg0, int arg1,
				com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onResetLock(ExtendedBluetoothDevice arg0,
				com.ttlock.bl.sdk.entity.Error arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSearchDeviceFeature(ExtendedBluetoothDevice arg0,
				int arg1, int arg2, com.ttlock.bl.sdk.entity.Error arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSetAdminKeyboardPassword(ExtendedBluetoothDevice arg0,
				String arg1, com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSetBongKey(com.ttlock.bl.sdk.entity.Error arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSetDeletePassword(ExtendedBluetoothDevice arg0,
				String arg1, com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSetLockName(ExtendedBluetoothDevice arg0, String arg1,
				com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSetLockTime(ExtendedBluetoothDevice arg0,
				com.ttlock.bl.sdk.entity.Error arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSetMaxNumberOfKeyboardPassword(
				ExtendedBluetoothDevice arg0, int arg1,
				com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSetWristbandKey(ExtendedBluetoothDevice arg0, int arg1,
				com.ttlock.bl.sdk.entity.Error arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onUnlock(ExtendedBluetoothDevice arg0, int arg1, int arg2,
				long arg3, com.ttlock.bl.sdk.entity.Error error) {
			// 开锁成功后上传开锁记录
			if (error == error.SUCCESS) {
				toast("开门成功");
				if (ActivityPuTongKey.addLock) {
					ActivityPuTongKey.addLock = false;
					userPresenter
							.uploadHistoryOfUnlock(uid,
									ActivityPuTongKey.lockid, "1", arg1 + "",
									arg2 + "");
				}
				if (ActivityGuanLiKeyTwo.addLock) {
					ActivityGuanLiKeyTwo.addLock = false;
					userPresenter.uploadHistoryOfUnlock(uid,
							ActivityGuanLiKeyTwo.lockid, "1", arg1 + "", arg2
									+ "");
				} else {
					userPresenter.uploadHistoryOfUnlock(uid, lockid, "1", arg1
							+ "", arg2 + "");
				}

			}
		}

		@Override
		public void onLock(ExtendedBluetoothDevice arg0, int arg1,
				com.ttlock.bl.sdk.entity.Error arg2) {

		}
	};

	@Override
	public void onMyActivityCreated() {
		add_shap_title_tv.setText("我的智能锁");
		close_icon.setVisibility(View.GONE);
		context = this;
		save.setVisibility(View.VISIBLE);
		save.setText("备份钥匙");

		userPresenter = new UserPresenter(this);
		keyPresenter = new KeyPresenter(this);
		myKeyService = new MyKeyService(getActivity());
		init();

		String sciner = SPUtils.get(getActivity(), null,
				SPContants.ScienerUsername, "") + "";// 科技侠账号

		uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
		panduan(uid);

		accessToken = MyPreference.getStr(getActivity(),
				MyPreference.ACCESS_TOKEN);
		// 请求打开蓝牙
		mTTLockAPI.requestBleEnable(getActivity());
		mTTLockAPI.startBleService(getActivity());
		// 请求位置权限成功打开蓝牙
		mTTLockAPI.startBTDeviceScan();

		xlistview.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public void onMenuItemClick(int position, SwipeMenu menu, int index) {
				deKeyId = keyBean.get(position).getKeyId();
				if (menu.getMenuItem(index).getTitle().equals("删除钥匙")) {
					userPresenter.deleteKey(uid, uid, keyBean.get(position)
							.getKeyId(), keyBean.get(position).getLockId());
				} else if (menu.getMenuItem(index).getTitle().equals("取消绑定")) {
					userPresenter.unbindLock(uid, keyBean.get(position)
							.getLockId());
				}
			}
		});
		xlistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				curKey = keyBean.get(position);

				lockid = keyBean.get(position).getLockId();
				type = keyBean.get(position).getType();
				if (keyBean.get(position).getType().equals("0")) {

					if (keyBean.get(position).getStatus().equals("110404")) {
						ByAlert.alert("该钥匙冻结中");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110405")) {
						ByAlert.alert("该钥匙已冻结");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110406")) {
						ByAlert.alert("该钥匙解除冻结中");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110407")) {
						ByAlert.alert("该钥匙删除中");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110408")) {
						ByAlert.alert("该钥匙已删除");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110409")) {
						ByAlert.alert("该钥匙重置中");
					}
					if (keyBean.get(position).getStatus().equals("110410")) {
						ByAlert.alert("该钥匙已重置");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110411")) {
						ByAlert.alert("该钥匙修改中");
						return;
					}
					Intent intent = new Intent(getActivity(),
							ActivityGuanLiKey.class);
					intent.putExtra("keyName", keyBean.get(position)
							.getLockId());
					intent.putExtra("lockid", lockid);
					intent.putExtra("type", type);
					intent.putExtra("keyid", keyBean.get(position).getKeyId());
					intent.putExtra("model", keyBean.get(position));
					intent.putExtra("lockMac", keyBean.get(position)
							.getLockMac());
					intent.putExtra("lockAlias", keyBean.get(position)
							.getLockAlilas());
					startActivity(intent);

				} else {
					if (keyBean.get(position).getStatus().equals("110404")) {
						ByAlert.alert("该钥匙冻结中");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110405")) {
						ByAlert.alert("该钥匙已冻结");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110406")) {
						ByAlert.alert("该钥匙解除冻结中");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110407")) {
						ByAlert.alert("该钥匙删除中");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110408")) {
						ByAlert.alert("该钥匙已删除");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110409")) {
						ByAlert.alert("该钥匙重置中");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110410")) {
						ByAlert.alert("该钥匙已重置");
						return;
					}
					if (keyBean.get(position).getStatus().equals("110411")) {
						ByAlert.alert("该钥匙修改中");
						return;
					}

					Intent intent = new Intent(getActivity(),
							ActivityPuTongKey.class);
					intent.putExtra("lockMac", keyBean.get(position)
							.getLockMac());
					intent.putExtra("lockid", lockid);
					intent.putExtra("keyid", keyBean.get(position).getKeyId());
					intent.putExtra("lockName", keyBean.get(position)
							.getLockAlilas());
					startActivity(intent);

				}
			}
		});

	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// panduan(uid);
	}

	@SuppressLint("NewApi")
	private void init() {
		mContext = getActivity();
		MyApplcation.getInstance()
				.registerActivityLifecycleCallbacks(callbacks);
		initGreenDao();
		initTTLock();
	}

	@SuppressLint("NewApi")
	ActivityLifecycleCallbacks callbacks = new ActivityLifecycleCallbacks() {
		@Override
		public void onActivityCreated(Activity activity,
				Bundle savedInstanceState) {

		}

		@Override
		public void onActivityStarted(Activity activity) {

		}

		@Override
		public void onActivityResumed(Activity activity) {
			curActivity = activity;
		}

		@Override
		public void onActivityPaused(Activity activity) {

		}

		@Override
		public void onActivityStopped(Activity activity) {

		}

		@Override
		public void onActivitySaveInstanceState(Activity activity,
				Bundle outState) {

		}

		@Override
		public void onActivityDestroyed(Activity activity) {
			// TODO:
			curActivity = null;
		}

	};

	/**
	 * 数据库初始化
	 */
	private void initGreenDao() {
		DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(
				getActivity(), "zhujia.db", null);
		Database db = helper.getWritableDb();
		daoSession = new DaoMaster(db).newSession();
		keyDao = daoSession.getKeyDao();

	}

	/**
	 * 通通锁初始化操作
	 */
	private void initTTLock() {
		mTTLockAPI = new TTLockAPI(mContext, mTTLockCallback);
	}

	private <K, V extends Parcelable> void broadcastUpdate(String action,
			K key, V value) {
		Intent intent = new Intent(action);
		if (key != null) {
			Bundle bundle = new Bundle();
			bundle.putParcelable((String) key, value);
			intent.putExtras(bundle);
		}
		MyApplcation.ctx.sendBroadcast(intent);
	}

	public static DaoSession getDaoSession() {
		return daoSession;
	}

	private void toast(final String msg) {
		handler.post(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
			}
		});
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
	}

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	/**
	 * 数据库里面的key
	 */
	private void read() {

		List<KeyBean> userlist = myKeyService.getAllUserList();
		if (null != userlist && userlist.size() > 0) {// 当数据库中有数据的话 从数据库中读取
			adapter = new KeyAdapter(getActivity(), getData(),
					R.layout.item_my_key);
			xlistview.setAdapter(adapter);
			adapter.notifyDataSetChanged();
		}
	}

	/**
	 * 从数据库读取listview数据
	 * 
	 * @return
	 */
	private List<KeyBean> getData() {
		keyBean = new ArrayList<KeyBean>();

		List<KeyBean> userlist = myKeyService.getAllUserList();

		if (null != userlist && userlist.size() > 0) {
			for (int i = 0; i < userlist.size(); i++) {
				KeyBean beans = new KeyBean();
				setCreator(userlist.get(i).getType());
				beans.setLockId(userlist.get(i).getLockId());
				beans.setKeyId(userlist.get(i).getKeyId());
				beans.setStart(userlist.get(i).getStart());
				beans.setEnd(userlist.get(i).getEnd());
				beans.setCreateTime(userlist.get(i).getCreateTime());
				beans.setUpdateTime(userlist.get(i).getUpdateTime());
				beans.setStatus(userlist.get(i).getStatus());
				beans.setType(userlist.get(i).getType());
				beans.setLockAlilas(userlist.get(i).getLockAlilas());
				beans.setHouseNo(userlist.get(i).getHouseNo());
				beans.setUserType(userlist.get(i).getUserType());
				beans.setLockMac(userlist.get(i).getLockMac());
				beans.setPush(userlist.get(i).getPush());
				beans.setKeyStatus(userlist.get(i).getKeyStatus());
				beans.setIsNew(userlist.get(i).getIsNew());

				keyBean.add(beans);
			}
		}
		return keyBean;
	}

	/**
	 * 判断是否登录
	 * 
	 * @param uid
	 */
	public void panduan(String uid) {
		if (uid == null) {
			img_nodata.setVisibility(View.VISIBLE);
			img_nodata.setText("请先登录");
			xlistview.setVisibility(View.GONE);
		} else {
			if (uid.equals("")) {
				img_nodata.setVisibility(View.VISIBLE);
				img_nodata.setText("请先登录");
				xlistview.setVisibility(View.GONE);
			} else {
				userPresenter.myKey(uid);
			}
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.mykey_sousuo:// 搜索
			intent = new Intent(getActivity(), ActivityMyKeySouSuo.class);
			startActivity(intent);
			break;
		case R.id.img_nodata:
			if (img_nodata.getText().toString().equals("请先登录")) {
				getActivity().startActivity(
						new Intent(getActivity(), LoginActivity.class));
			}
			break;
		case R.id.save://备份
//			intent = new Intent(getActivity(), ActivityMyKey.class);
//			startActivity(intent);
			LoginController.beifen(getActivity(), null);
			break;
		case R.id.mykey_add:// 添加钥匙
			intent = new Intent(getActivity(), ActivitySheBei.class);
			startActivity(intent);
			break;
		case R.id.mykey_yuyue:// 预约安装
			intent = new Intent(getActivity(), ActivityKeyYuYue.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == KeyPresenter.register_success) {
				SPUtils.put(getActivity(), null, SPContants.ScienerUsername,
						entity.getData().toString());
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == KeyPresenter.register_fail) {
				ByAlert.alert(entity.getData());
			}

			else if (entity.getEventType() == KeyPresenter.addMain_success) {
				BangDingBean bean = (BangDingBean) entity.getData();
				// 添加管理员成功之后直接备份钥匙
				keyPresenter.getBeiFei(uid, bean.getLock_id(),
						bean.getKey_id(), adminPs01 + "", adminKeyboardPwd01
								+ "", deletePwd01 + "");
				// 添加管理员成功之后 重置键盘密码
				keyPresenter.getJianPanPass(uid, bean.getLock_id(), pwdInfo01
						+ "", timestamp01 + "");

				Toast.makeText(getActivity(), "添加管理员成功", 2000).show();
				Log.v(TAG, entity.getData().toString());

			} else if (entity.getEventType() == KeyPresenter.addMain_fail) {
				Toast.makeText(getActivity(), "添加管理员失败", 2000).show();
			} else if (entity.getEventType() == UserPresenter.myKey_success) {
				keyBean = (List<KeyBean>) entity.getData();
				if (keyBean != null) {
					if (keyBean.size() > 0) {
						myKeyService.deleteData();
						setCreator(keyBean.get(0).getType());
						adapter = new KeyAdapter(getActivity(), keyBean,
								R.layout.item_my_key);
						xlistview.setAdapter(adapter);
						img_nodata.setVisibility(View.GONE);
						xlistview.setVisibility(View.VISIBLE);

						KeyBean beans = new KeyBean();
						for (int i = 0; i < keyBean.size(); i++) {
							beans.setLockId(keyBean.get(i).getLockId());
							beans.setKeyId(keyBean.get(i).getKeyId());
							beans.setStart(keyBean.get(i).getStart());
							beans.setEnd(keyBean.get(i).getEnd());
							beans.setCreateTime(keyBean.get(i).getCreateTime());
							beans.setUpdateTime(keyBean.get(i).getUpdateTime());
							beans.setStatus(keyBean.get(i).getStatus());
							beans.setType(keyBean.get(i).getType());
							beans.setLockAlilas(keyBean.get(i).getLockAlilas());
							beans.setHouseNo(keyBean.get(i).getHouseNo());
							beans.setUserType(keyBean.get(i).getUserType());
							beans.setLockMac(keyBean.get(i).getLockMac());
							beans.setPush(keyBean.get(i).getPush());
							beans.setKeyStatus(keyBean.get(i).getKeyStatus());
							beans.setIsNew(keyBean.get(i).getIsNew());
							myKeyService.add(beans);// 存放到数据库
						}

					} else {
//						img_nodata.setVisibility(View.VISIBLE);
//						img_nodata.setText("没有钥匙哦...");
//						xlistview.setVisibility(View.GONE);
						liner_nokey.setVisibility(View.VISIBLE);
						xlistview.setVisibility(View.GONE);
						img_nodata.setVisibility(View.GONE);
					}
				} else {
//					img_nodata.setText("没有钥匙哦...");
//					img_nodata.setVisibility(View.VISIBLE);
//					xlistview.setVisibility(View.GONE);
					liner_nokey.setVisibility(View.VISIBLE);
					xlistview.setVisibility(View.GONE);
					img_nodata.setVisibility(View.GONE);
				}
			} else if (entity.getEventType() == UserPresenter.myKey_fail) {
				ByAlert.alert(entity.getData());
			}
			// 删除钥匙
			if (entity.getEventType() == UserPresenter.deleteKey_success) {
				ByAlert.alert(entity.getData());
				Iterator<KeyBean> iterator = keyBean.iterator();
				while (iterator.hasNext()) {
					KeyBean bean = iterator.next();
					if (deKeyId.equals(bean.getKeyId())) {
						// DbService.deleteKey(curKey);
						iterator.remove();
						adapter.notifyDataSetChanged();
						break;
					}
				}
			} else if (entity.getEventType() == UserPresenter.deleteKey_fail) {
				ByAlert.alert(entity.getData());
			}
			// 解除绑定
			if (entity.getEventType() == UserPresenter.unbindAdmin_success) {
				ByAlert.alert(entity.getData());
				Iterator<KeyBean> iterator = keyBean.iterator();
				while (iterator.hasNext()) {
					KeyBean bean = iterator.next();
					if (deKeyId.equals(bean.getKeyId())) {
						iterator.remove();
						myKeyService.deletekey(deKeyId);
						adapter.notifyDataSetChanged();
						break;
					}
				}
			} else if (entity.getEventType() == UserPresenter.unbindAdmin_fail) {
				ByAlert.alert(entity.getData());
			}
			if (entity.getEventType() == UserPresenter.uploadjilu_success) {
				ByAlert.alert(entity.getData());
				// ByAlert.alert("开门成功");//上传记录的地方，在开锁后上传开锁记录
			} else if (entity.getEventType() == UserPresenter.uploadjilu_fail) {
				ByAlert.alert(entity.getData());
			}
			// 备份钥匙
			if (entity.getEventType() == KeyPresenter.beifen_success) {
			} else if (entity.getEventType() == KeyPresenter.beifen_fail) {
			}
			// 重置键盘密码
			if (entity.getEventType() == KeyPresenter.jianpanPass_success) {
			} else if (entity.getEventType() == KeyPresenter.jianpanPass_fail) {
			}
		}
	}

	/**
	 * 刷新
	 */
	public void refresh() {
		adapter = new KeyAdapter(getActivity(), null, R.layout.item_my_key);
		adapter.notifyDataSetChanged();
	}

	private void setCreator(final String type) {

		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// TODO Auto-generated method stub
				SwipeMenuItem item2 = new SwipeMenuItem(getActivity());
				item2.setBackground(new ColorDrawable(Color.rgb(0xff, 0x6e,
						0xa5)));
				item2.setWidth(dp2px(90));
				if (type.equals("0")) {
					item2.setTitle("取消绑定");
				} else {
					item2.setTitle("删除钥匙");
				}
				item2.setTitleSize(18);
				item2.setTitleColor(Color.parseColor("#ffffff"));
				// item2.setIcon(R.drawable.ic_action_discard);
				menu.addMenuItem(item2);
			}
		};
		xlistview.setMenuCreator(creator);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == getActivity().RESULT_OK) {
			if (requestCode == TTLockAPI.REQUEST_ENABLE_BT) {
				// 打开蓝牙之后启动扫描
				mTTLockAPI.startBTDeviceScan();
			}
		}
		if (requestCode == 104) {// 当从搜索页面返回时 加载数据
			String lock_alias = data.getStringExtra("lock_alias");
			List<KeyBean> b = new ArrayList<KeyBean>();
			b = (List<KeyBean>) myKeyService.aliasQuery(lock_alias);
			adapter = new KeyAdapter(getActivity(), b, R.layout.item_my_key);
			xlistview.setAdapter(adapter);
		}
	}
}
